package com.base.kongjian.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import cn.mysteel.util.ObjectUtils;

import com.base.kongjian.dao.MessageDAO;
import com.base.kongjian.entity.Message;
import com.base.kongjian.service.MessageService;
import com.mysteel.page.Page;

@Service("messageService")
public class MessagServiceImpl implements MessageService
{
	@Autowired
	private MessageDAO messageDao;
	@Override
	public void sendMessage(Message message)
	{
		Assert.notNull (message);;
		
		message.setCreateTime (System.currentTimeMillis ());

		
		messageDao.save (message);
	}
	
	@Override
	public void deleteMessageById(long id)
	{
		Message message = messageDao.get (id);
		
		if(ObjectUtils.notNull (message))
		{
			messageDao.delete (id);
		}
	}
	
	@Override
	public Message getMessageById(long id)
	{
		Message message = messageDao.get (id);
		

		
		return message;
	}
	
	@Override
	public Page<Message> queryMessage(Map<String, Object> params,int currentPageNum, int maxPageRowCount)
	{
		
		Page<Message> page = null;

		if (ObjectUtils.isNull(params))
		{
			params = new HashMap<String, Object>(2);
		}
		
		int count = messageDao.count(params);

		if (count > 0)
		{
			page = new Page<Message>();
			page.setTotalRowCount(count);
			page.setCurrentPageNum(currentPageNum);
			page.setMaxPageRowCount(maxPageRowCount);
			page.setURL(params);

			params.put("startPageRowCount", page.getStartPageRowCount());
			params.put("maxPageRowCount", page.getMaxPageRowCount());

			List<Long> MessageIds = messageDao.query(params);

			if (ObjectUtils.notEmpty(MessageIds))
			{
				List<Message> Messages = new ArrayList<Message>(MessageIds.size());

				for (long MessageId : MessageIds)
				{
					Messages.add(getMessageById(MessageId));
				}

				page.setDatas(Messages);
			}
		}

		return page;
	}

	@Override
	public void updateMessage(Message message)
	{
		Assert.notNull (message);
		
		long id = message.getId ();
		
		Message ms = messageDao.get (id);
		
		if(ObjectUtils.notNull (ms))
		{
			ms.setStatus (message.getStatus ());
			
			messageDao.update (ms);
		}
	}

	@Override
	public long getUnReadCount(long memberId)
	{
		Map<String,Object> params = new HashMap<String,Object>();
		
		params.put ("memberId" ,memberId);
		
		params.put ("status" ,1);
		
		return messageDao.count (params);
	}

	@Override
	public long getReadCount(long memberId)
	{
		Map<String,Object> params = new HashMap<String,Object>();
		
		params.put ("memberId" ,memberId);
		
		params.put ("status" ,2);
		
		return messageDao.count (params);
	}
}
